"use client";

import { ChevronDownIcon } from "@chakra-ui/icons";
import { Button, Menu, MenuButton, MenuItem, MenuList } from "@chakra-ui/react";
import { useEffect, useMemo, useState } from "react";

export type ConfigOption =  {
  name: string,
  value: number
}
export type SelectMenuOption = {
  name: string;
  value: number;
};

function SelectMenu({
  select = 0,
  options,
  onChange,
}: {
  select?: number;
  options: SelectMenuOption[];
  onChange?: (index: number) => void;
}) {
  const [currentSelect, setCurrentSelect] = useState(0);
  const currentSelectOption = useMemo(() => {
    return options[currentSelect] || "";
  }, [currentSelect, options]);

  useEffect(() => {
    setCurrentSelect(select);
  }, [select]);

  const changeSelect = (index: number) => {
    setCurrentSelect(index);
    onChange && onChange(index);
  };

  return (
    <Menu>
      <MenuButton
        as={Button}
        rightIcon={<ChevronDownIcon fill={"#000"} boxSize={"5"} />}
        w={"100%"}
        textAlign={"left"}
        className="selecet-menu-btn !rounded-md"
        bg="rgba(255, 255, 255, 0.95)"
        color="#000"
        fontWeight="medium"
        borderColor="rgba(255, 150, 0, 0.4)"
        border="1px solid"
        _hover={{ bg: "rgba(255, 255, 255, 1)", borderColor: "rgba(255, 150, 0, 0.6)" }}
        _active={{ bg: "rgba(255, 150, 0, 0.1)" }}
        boxShadow="0 1px 3px rgba(0, 0, 0, 0.05)"
        height="45px"
        fontSize="md"
      >
        {currentSelectOption.name}
      </MenuButton>
      <MenuList
        padding={0}
        overflow={"hidden"}
        zIndex={10}
        bg="white"
        borderColor="rgba(255, 150, 0, 0.2)"
        boxShadow="0 4px 12px rgba(0, 0, 0, 0.1)"
        borderRadius="md"
      >
        {options.map((option, index) => (
          <MenuItem
            key={index}
            className="select-menu-item"
            bg="white"
            color="black"
            _hover={{ bg: "rgba(255, 150, 0, 0.8)", color: "white" }}
            _focus={{ bg: "rgba(255, 150, 0, 0.8)", color: "white" }}
            fontWeight="medium"
            borderBottom={index < options.length-1 ? "1px solid rgba(0, 0, 0, 0.05)" : "none"}
            onClick={() => changeSelect(index)}
          >
            {option.name}
          </MenuItem>
        ))}
      </MenuList>
    </Menu>
  );
}

export default SelectMenu;
